using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using Microsoft.SharePoint;
using Microsoft.Web.CommandUI;
using Microsoft.SharePoint.Taxonomy;
using Mvw.SharePoint.Taxonomy.AutoTagging.Licenses;

namespace Mvw.SharePoint.Taxonomy.AutoTagging
{
	/// <summary>
	/// Enables ContentTypes for the Workspaces list and ensures that SharePoint's TaxonomyFieldAdded feature is activated.
    /// The real work, for example adding managed metadata columns to the Workspaces list, is done in the PopulateWorkspacesList
    /// routine. Via this page and routine the Workspaces list is reset as follows:
    /// - List is emptied
    /// - (New) Columns are added
    /// - Web application is scanned for Workspaces (optionally you can import all site collections)
    /// - For each Workspace / site collection a "new" list entry is created
    /// Furthermore through this feature the PopulateList custom action and attaches 3 list event receivers are added
	/// </summary>
	/// <remarks>
    /// The GUID attached to this class may be used during packaging and should not be modified.
	/// </remarks>

	[Guid("e3137409-07c5-4ecf-8a2e-3592734d6484")]
	public class AdminInfrastructureFeatureReceiver : SPFeatureReceiver
	{
		public override void FeatureActivated(SPFeatureReceiverProperties properties)
		{
            using (var currSite = new SPSite((properties.Feature.Parent as SPWeb).Site.ID))
            {
                using (var currWeb = currSite.OpenWeb((properties.Feature.Parent as SPWeb).ID))
			    {
				    // Only continue if the feature's parent web is a root web
                    // TODO Ensure that the feature is enabled only once per web application
				    if(!currWeb.ID.Equals(currWeb.Site.RootWeb.ID))
				    {
					    return;
				    }

                    // Trial License -> This should be commented out for the retail version 
                    TrialLicense.verifyTrialStartDate(currWeb);
                    
                    // Ensure that Self Service SiteCollection Creation is enabled
                    // TODO update documentation that SSSC is automatically switched on
                    // TODO this probably needs farm admin permissions but better to leave it like this and 
                    //      have the administrator activate the feature or request SSSC to be enabled manually
                    try
                    {
                        if (!currSite.WebApplication.SelfServiceSiteCreationEnabled)
                        {
                            currSite.WebApplication.SelfServiceSiteCreationEnabled = true;
                            currSite.WebApplication.Update();
                        }
                    }
                    catch { }

                    // Enable content types for our list
                    var workspaceList = currWeb.Lists.TryGetList("Workspaces");
                    if (workspaceList == null)
                    {
                        return;
                    }
                    workspaceList.ContentTypesEnabled = true;
                    workspaceList.Update();

                    // Ensure that SharePoint's TaxonomyFieldAdded feature is enabled for this site collection
                    currWeb.EnsureRequiredFeatures(true, false, true);

                    // Try and update the three Workspace choice columns (managed path, lanugage and web template)
                    // However, if the routine fails the execution of the feature receiver should not be interrupted
                    try
                    {
                        Ext.ResetWorkspaceColumns(currWeb, currSite);
                    }
                    catch { }

                    // Initialize a number of setting properties that later may be change through the UI
                    var workspacesSettings = new Dictionary<string, string>();
                    workspacesSettings.Add("WSAlwaysUpdateListElements", false.ToString());
                    workspacesSettings.Add("WSDeleteWorkspaces", false.ToString());
                
                    currWeb.AllProperties["WorkspacesSettings"] = workspacesSettings.DictionaryToString();
                    currWeb.Update();
			    }
            }
		}

		public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
		{
			using (var currWeb = properties.Feature.Parent as SPWeb)
			{
				var siteCollectionsList = currWeb.Site.RootWeb.Lists.TryGetList("Workspaces");
				{
                    if (siteCollectionsList == null)
                    {
                        return;
                    }
				}
				siteCollectionsList.Delete();
			}
		}
	}
}
